function varargout = TLIsrDlg(action,varargin)

% TL_ISR_DLG manages the user interface of TargetLink ISR block.
%
% SYNTAX dlgInfo = TLIsrDlg('GetDlgInfo');
%   gets dialog info of TargetLink ISR block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLIsrDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLIsrDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLIsrDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLIsrDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLIsrDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLIsrDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/MultirateBlockset/MultirateBlockset_UI/Sources/MSrc/project.pj $
% $Revision: 1.12 $
% $Date: 2011/03/18 07:24:06MEZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('rtos');
        titleName = 'ISR';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames   = {
            'ISR'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'ISR'
                [sheetDims, ctrlPos] = FcnCalcIsrControlPositions(commonGeom);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;

    case 'Create',
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'ISR'
                dlgdata = FcnCreateIsrControls(pageNum,dlgfig,dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage',
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
        switch pageName
            case 'ISR'
                [dlgdata, bModified] = ...
                    FcnManageIsrControls(pageNum,dlgfig,dlgdata,pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};

        pageName  = dlgdata.pageNames{pageNum};

        switch pageName
            case 'ISR'
                dlgdata = FcnUpdateIsrControls(dlgdata, dlgfig, pageNum);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata = varargin{2};
        bClose   = varargin{3};
        FcnApply(dlgdata);
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action: "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnCalcIsrControlPositions calculates positions for all ISR controls
%
% INPUT ARGUMENTS
%   commonGeom		common geometry values
%
% OUTPUT ARGUMENTS
%   sheetDims		dimension of sheet
%   ctrlPos		calculated positios of al controls
%
% HINT:
% Positions are calculated from the bottom left of the fig to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcIsrControlPositions(commonGeom)

strings_and_styles = {...
    'Function class: ', 	    'text';...
    repmat('m',1,24),           'edit'; ...
    ' Delete ISR ',             'pushbutton'; ...
    '  . . .   '                'text'};

[isrLabelSize, ...
    isrPopupSize, ...
    deleteIsrButtonSize, ...
    dotButtonSize] = ...
    ds_get_uicontrol_sizes(commonGeom, strings_and_styles);

widths = [ ...
    isrLabelSize(1), ...      % max of label width in first column
    isrPopupSize(1), ...
    dotButtonSize(1)];
[col,colWidth,colDelta,rowDelta] = ds_get_gui_columns(widths,commonGeom);

% finetune some results
if (2 * deleteIsrButtonSize(1) + colDelta/3) > isrPopupSize(1)
    isrPopupSize(1) = 2 * deleteIsrButtonSize(1) + colDelta/3;
else
    deleteIsrButtonSize(1) = (isrPopupSize(1) - colDelta/3) / 2;
end

%-----------------------------------------------------------
% multirate common properties group box
%-----------------------------------------------------------
cx = commonGeom.figSideEdgeBuffer + commonGeom.sheetSideEdgeBuffer;
cy = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;

multirateGroupboxWidth = col(end) + ...
    colWidth(end) + ...
    commonGeom.frameSideEdgeBuffer;

multirateGroupboxHeight = ...
    commonGeom.frameTopEdgeBuffer + ...
    commonGeom.editHeight + ...
    commonGeom.frameBottomEdgeBuffer;

ctrlPos.multirateGroupbox =  ...
    [cx cy  multirateGroupboxWidth multirateGroupboxHeight];

%-----------------------------------------------------------
% 1st row
cy = commonGeom.frameBottomEdgeBuffer;

% category label
cx = col(1);
ctrlPos.categoryLabel = [cx cy isrLabelSize];

% category edit
cx = col(2);
ctrlPos.categoryPopup = [cx cy isrPopupSize];

%-----------------------------------------------------------
% ISR group box
%-----------------------------------------------------------
cx = ctrlPos.multirateGroupbox(1);
cy = ctrlPos.multirateGroupbox(2) + ctrlPos.multirateGroupbox(4) + commonGeom.textHeight;

isrGroupboxWidth = multirateGroupboxWidth;

isrGroupboxHeight = ...
    commonGeom.frameTopEdgeBuffer + ...
    4 * rowDelta + ...
    5 * commonGeom.editHeight + ...
    commonGeom.frameBottomEdgeBuffer;
ctrlPos.isrGroupbox =  ...
    [cx cy  isrGroupboxWidth isrGroupboxHeight];

%-----------------------------------------------------------
% 5th row
cy = commonGeom.frameBottomEdgeBuffer;

% function class
cx = col(1);
ctrlPos.functionClassLabel = [cx cy isrLabelSize];

cx = col(2);
ctrlPos.functionClassEdit = [cx cy isrPopupSize];

cx = col(3);
ctrlPos.functionClassDotButton = [cx cy dotButtonSize(1) isrPopupSize(2)];

%-----------------------------------------------------------
% 4th row
cy = cy + isrPopupSize(2) + rowDelta;

% code file
cx = col(1);
ctrlPos.moduleLabel = [cx cy isrLabelSize];

cx = col(2);
ctrlPos.moduleEdit = [cx cy isrPopupSize];

cx = col(3);
ctrlPos.moduleDotButton = [cx cy dotButtonSize(1) isrPopupSize(2)];

%-----------------------------------------------------------
% 3th row
cy = cy + isrPopupSize(2) + rowDelta;

% description
cx = col(1);
ctrlPos.descriptionLabel = [cx cy isrLabelSize];

cx = col(2);
ctrlPos.descriptionEdit = [cx cy isrPopupSize];

%-----------------------------------------------------------
% 2nd row
cy = cy + isrPopupSize(2) + rowDelta;

% new ISR push button
cx = col(2);
ctrlPos.newIsrButton = [cx cy deleteIsrButtonSize];

% delete ISR push button
cx = col(2) + deleteIsrButtonSize(1) + colDelta/3;
ctrlPos.deleteIsrButton = [cx cy deleteIsrButtonSize];

%-----------------------------------------------------------
% 1st row
cy = cy + deleteIsrButtonSize(2) + rowDelta;

% ISR
cx = col(1);
ctrlPos.isrLabel = [cx cy isrLabelSize];

cx = col(2);
ctrlPos.isrPopup = [cx cy isrPopupSize];


% sheet dimensions
sheetDims(1) = ctrlPos.isrGroupbox(3) + ...
    2 * commonGeom.frameSideEdgeBuffer;

sheetDims(2) = ctrlPos.isrGroupbox(4) + ...
    commonGeom.textHeight + ...
    ctrlPos.multirateGroupbox(4) + ...
    commonGeom.textHeight + ...
    commonGeom.sheetBottomEdgeBuffer;


%-----------------------------------------------------------------------------------------
% FcnCreateIsrControls creates all ISR controls
%
% INPUT ARGUMENTS
%   pageNum 	number of current page (=1 for ISR page)
%   dlgfig      dialog figure handle
%   dlgdata 	dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata 	modified diaog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateIsrControls(pageNum,dlgfig,dlgdata)

ctrlPos    = dlgdata.pageData{pageNum}.ctrlPos;
Children   = dlgdata.pageData{pageNum}.children;

% ISR groupbox
Children.isrGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'ISR definition'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.isrGroupbox);

% ISR popup
Children.isrLabel = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'Style',              'text', ...
    'String',             'ISR name:', ...
    'Position',           ctrlPos.isrLabel);

Children.isrPopup = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'Popupmenu', ...
    'String',             ' ', ...
    'Position',           ctrlPos.isrPopup);

% new / delete ISR button
Children.newIsrButton = uicontrol( ...
    'Parent',            Children.isrGroupbox, ...
    'Style',             'pushbutton', ...
    'String',            'New ISR', ...
    'Position',          ctrlPos.newIsrButton);

Children.deleteIsrButton = uicontrol( ...
    'Parent',            Children.isrGroupbox, ...
    'Style',             'pushbutton', ...
    'String',            'Delete ISR', ...
    'Position',          ctrlPos.deleteIsrButton);

Children.descriptionLabel = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'Style',              'text', ...
    'String',             'Description:', ...
    'Position',           ctrlPos.descriptionLabel);

Children.descriptionEdit = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.descriptionEdit);

Children.moduleLabel = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'Style',              'text', ...
    'String',             'Module:', ...
    'Position',           ctrlPos.moduleLabel);

Children.moduleEdit = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.moduleEdit);

Children.moduleDotButton = uicontrol( ...
    'Parent',            Children.isrGroupbox, ...
    'Style',             'pushbutton', ...
    'String',            ' . . . ', ...
    'Position',          ctrlPos.moduleDotButton);

Children.functionClassLabel = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'Style',              'text', ...
    'String',             'Function class:', ...
    'Position',           ctrlPos.functionClassLabel);

Children.functionClassEdit = uicontrol( ...
    'Parent',             Children.isrGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.functionClassEdit);

Children.functionClassDotButton = uicontrol( ...
    'Parent',            Children.isrGroupbox, ...
    'Style',             'pushbutton', ...
    'String',            ' . . . ', ...
    'Position',          ctrlPos.functionClassDotButton);

% multirate common properties groupbox
Children.multirateGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Multirate common properties'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.multirateGroupbox);

% category
Children.categoryLabel = uicontrol( ...
    'Parent',             Children.multirateGroupbox, ...
    'Style',              'text', ...
    'String',             'Category:', ...
    'Position',           ctrlPos.categoryLabel);

Children.categoryPopup = uicontrol( ...
    'Parent',             Children.multirateGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'Popupmenu', ...
    'String',             {'CAT1_NO_OS_CALLS', 'CAT2_WITH_OS_CALLS'}, ...
    'Position',           ctrlPos.categoryPopup);

dlgdata.pageData{pageNum}.children = Children;

dlgdata = FcnGetIsrDataFromDD(dlgdata);


%-----------------------------------------------------------------------------------------
% FcnManageIsrControls manage control actions of ISR page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageIsrControls(pageNum,dlgfig,dlgdata,pageAction)    %#ok

Children   = dlgdata.pageData{pageNum}.children;

% determine the current ISR control
currentIsr       = dlgdata.data.isr;
isrList          = dlgdata.isrInfo.dataStrings;
currentIsrIdx    = find(strcmp(currentIsr,isrList));

switch pageAction
    case 'isrPopup'
        newIsrIdx = get(Children.isrPopup, 'Value');
        if ~isequal(currentIsrIdx, newIsrIdx)
            if isempty(currentIsrIdx)
                % current ISR is not found in ISR list
                newIsrIdx = newIsrIdx - 1;
                if newIsrIdx == 0
                    bModified = 0;
                    return
                end
            end
            dlgdata.data.isr = dlgdata.isrInfo.dataStrings{newIsrIdx};
            bModified = 1;
        end
    case 'newIsrButton'
        [dlgdata, bModified] = FcnNewIsr(dlgdata);
    case 'deleteIsrButton'
        dlgdata = FcnDeleteIsr(dlgdata);
        bModified = 1;
    case 'descriptionEdit'
        dlgdata.isrData(currentIsrIdx).description = ...
            get(Children.descriptionEdit, 'String');
        dlgdata.isrInfo.editedIsr = unique([dlgdata.isrInfo.editedIsr,currentIsr]);
        bModified = 1;
    case 'moduleEdit'
        dlgdata.isrData(currentIsrIdx).module = ...
            get(Children.moduleEdit, 'String');
        dlgdata.isrInfo.editedIsr = unique([dlgdata.isrInfo.editedIsr,currentIsr]);
        bModified = 1;
    case 'moduleDotButton'
        dlgdata.isrData(currentIsrIdx).module = ...
            dsdd( 'SelectObject', ...
            'CurrentPath',     dlgdata.isrData(currentIsrIdx).module, ...
            'ObjectKind',      'Module');
        dlgdata.isrInfo.editedIsr = unique([dlgdata.isrInfo.editedIsr,currentIsr]);
        bModified = 1;
    case 'functionClassEdit'
        functionClassStr = get(Children.functionClassEdit, 'String');
        if isempty(functionClassStr),
            functionClassStr = 'default ';
        end
        dlgdata.isrData(currentIsrIdx).functionclass = functionClassStr;
        bModified = 1;
    case 'functionClassDotButton'
        dlgdata.isrData(currentIsrIdx).functionclass = ...
            dsdd( 'SelectObject', ...
            'CurrentPath',     dlgdata.isrData(currentIsrIdx).functionclass, ...
            'ObjectKind',      'FunctionClass');
        bModified = 1;
    case 'categoryPopup'
        dlgdata.isrData(currentIsrIdx).category = get(Children.categoryPopup, 'Value');
        dlgdata.isrInfo.editedIsr = unique([dlgdata.isrInfo.editedIsr,currentIsr]);
        bModified = 1;
end


%--------------------------------------------------------------------------
% FcnUpdateIsrControls updates the controls of the ISR tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number (=1 for ISR page)
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------

function dlgdata = FcnUpdateIsrControls(dlgdata, dlgfig, pageNum)          %#ok

Children = dlgdata.pageData{pageNum}.children;

isrData = dlgdata.isrData;

currentIsr = dlgdata.data.isr;
isrList    = dlgdata.isrInfo.dataStrings;
currentIsrIdx = find(strcmp(currentIsr,isrList));

enableOn = 'on';
if ~dlgdata.bIsFullVs
    enableOn = 'inactive';
end

% default control status for controls of ISR definition groupbox
isrPopupCtrlStatus               = struct('enable', enableOn, 'value', 1, 'string', {isrList});
newIsrButtonCtrlStatus           = struct('enable', enableOn);                                     %#ok
deleteIsrButtonCtrlStatus        = struct('enable', enableOn);
descriptionEditCtrlStatus        = struct('enable', enableOn, 'string', '');
moduleEditCtrlStatus             = struct('enable', enableOn, 'string', '');
moduleDotButtonCtrlStatus        = struct('enable', enableOn);
functionClassEditCtrlStatus      = struct('enable', enableOn, 'string', 'default ');
functionClassDotButtonCtrlStatus = struct('enable', enableOn);

% default control status for controls of multirate common properties groupbox
categoryPopupCtrlStatus         = struct('enable', enableOn, 'value', 2);
categoryPopupCtrlStatus.string  = {'CAT1_NO_OS_CALLS' 'CAT2_WITH_OS_CALLS'};

% if not valid disable most of the controls
if isempty(currentIsrIdx) ...
        || (~isempty(currentIsrIdx) && isrData(currentIsrIdx).bValid == 0),
    if isempty(currentIsrIdx)
        isrPopupCtrlStatus.string   = [{' '}, isrList];
    else
        isrPopupCtrlStatus.iserror = 1;
    end
    deleteIsrButtonCtrlStatus.enable = 'off';
    descriptionEditCtrlStatus.enable = 'inactive';
    moduleEditCtrlStatus.enable = 'inactive';
    moduleDotButtonCtrlStatus.enable = 'off';
    functionClassEditCtrlStatus.enable = 'inactive';
    functionClassDotButtonCtrlStatus.enable = 'off';

    % default control status for controls of multirate common properties groupbox
    categoryPopupCtrlStatus.enable = 'inactive';
else
    isrPopupCtrlStatus.value            = currentIsrIdx;
    descriptionEditCtrlStatus.string    = dlgdata.isrData(currentIsrIdx).description;
    moduleEditCtrlStatus.string       = dlgdata.isrData(currentIsrIdx).module;
    moduleEditCtrlStatus.iserror = ~isempty(dlgdata.isrData(currentIsrIdx).module) ...
        && ~dsdd('exist', ['/Pool/Modules/' dlgdata.isrData(currentIsrIdx).module]);
    functionClassEditCtrlStatus.string  = dlgdata.isrData(currentIsrIdx).functionclass;
    categoryPopupCtrlStatus.value       = dlgdata.isrData(currentIsrIdx).category;

    % check existence of function class
    functionClass = isrData(currentIsrIdx).functionclass;
    if ~dsdd('Exist',functionClass,'Parent','/Pool/FunctionClasses') ...
            && ~strcmp(functionClass,'default '),
        functionClassEditCtrlStatus.iserror = 1;
    end
end

ctrlsList = {
    'isrPopup' ...
    'newIsrButton' ...
    'deleteIsrButton' ...
    'descriptionEdit' ...
    'moduleEdit' ...
    'moduleDotButton' ...
    'functionClassEdit' ...
    'functionClassDotButton' ...
    'categoryPopup'};

for ctrlsNo=1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end
TLSetCtrlsStatus(dlgfig,Children, ctrlsList);


%--------------------------------------------------------------------------
% FcnNewIsr creates new ISR with default data
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag =1, if new alarm is created, =0 otherwise
%--------------------------------------------------------------------------
function [dlgdata, bModified] = FcnNewIsr(dlgdata)

% initialize return value
bModified = 0;

% ask user for ISR name
prompt   = 'Please enter a name for the isr.';
dlgTitle = 'ISR Name';
lineNum  = 1;
newIsrName = tl_deblank(char(inputdlg(prompt,dlgTitle,lineNum)),3);
if isempty(newIsrName),
   return;
end

isrData = dlgdata.isrData;

% check if ISR name is really new
isrList = dlgdata.isrInfo.dataStrings;
if any(strcmp(newIsrName,isrList));
    return
end

% check if current ISR is invalid and can be overwritten
currentIsr    = dlgdata.data.isr;
currentIsrIdx = find(strcmp(currentIsr,isrList));
if isempty(currentIsrIdx) || isrData(currentIsrIdx).bValid
    currentIsrIdx = length(isrList) + 1;
end
dlgdata.data.isr = newIsrName;

% initialize properties with default values
isrData = FcnSetIsrDefaults(isrData,currentIsrIdx);

% isrList must also be updated
dlgdata.isrInfo.dataStrings(currentIsrIdx) = {newIsrName};

% append ISR to list of new ISRs
dlgdata.isrInfo.newIsr = unique([dlgdata.isrInfo.newIsr, newIsrName]);
bModified = 1;

dlgdata.isrData = isrData;

 
%--------------------------------------------------------------------------
% FcnDeleteIsr remove current ISR
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function dlgdata = FcnDeleteIsr(dlgdata)

isrData = dlgdata.isrData;
isrInfo = dlgdata.isrInfo;

% get relevant indices
isrList = isrInfo.dataStrings;
delIsr  = dlgdata.data.isr;
delIsrIdx = find(strcmp(delIsr,isrList));

% add isrs to list of deleted ISR's
isrInfo.deletedIsr = unique([isrInfo.deletedIsr,delIsr]);

% remove ISR from list of new ISR's
idx = find(strcmp(delIsr,isrInfo.newIsr));
if ~isempty(idx),
    isrInfo.newIsr(idx) = [];
end

% purge property struct
isrInfo.dataStrings(delIsrIdx) = [];
isrData(delIsrIdx) = [];

% set updated value at uiControls
if isempty(isrInfo.dataStrings),
    % no more ISR available
    dlgdata.data.isr = ' ';
    isrInfo.dataStrings = {' '};
    isrData = FcnSetIsrDefaults([],1);
    isrData(1).bValid = 0;
else
    % select the first element from isrList
    dlgdata.data.isr = isrInfo.dataStrings{1};
end

dlgdata.isrData = isrData;
dlgdata.isrInfo = isrInfo;


%-------------------------------------------------------
% FcnGetIsrDataFromDD
%   gets all necessary data of ISRs from DD and puts it into an additional field 'isrData' of dlgdata
%
% INPUT ARGUMENTS
%   dlgdata      dialog data structure
%
% OUTPUT ARGUMENTS
%   dlgdata      modified dialog data structure
%-------------------------------------------------------
function dlgdata = FcnGetIsrDataFromDD(dlgdata)

% initialize lists holding added and deleted isrs
isrInfo.newIsr     = {};
isrInfo.deletedIsr = {};
isrInfo.editedIsr  = {};

currentIsr = dlgdata.data.isr;
% DataDictionary path for ISRs
ddIsrPath = '/Pool/RTOS/ISRs';
% retrieve ISR list from DataDictionary
[isrList, errCode] = dsdd('GetChildrenNames',ddIsrPath);
if dsdd_check_msg(errCode),
    return
end
if isempty(isrList),
    % no isrs available
    isrList = {currentIsr};
    isrIdx = 1;
    isrData = FcnSetIsrDefaults([],isrIdx);
    % mark ISR as not valid
    isrData.bValid = 0;
else
    % begin import ISR data
    isrData(1:length(isrList)) = FcnSetIsrDefaults([],1);
    for m = 1:length(isrList),
        isrName = isrList{m};
        isrObject = [ddIsrPath,'/',isrName];
        [bExist,hIsrObject] = dsdd('exist',isrObject);
        % description
        [isrData(m).description,errCode] = dsdd('GetDescription',hIsrObject);
        if dsdd_check_msg(errCode),
            isrData(m).description = '';
        end
        % module
        isrData(m).module = '';
        hModuleObject = dsdd('GetModuleRefTarget', hIsrObject);
        if ~isempty(hModuleObject)
            [isrData(m).module,errCode] = dsdd('GetAttribute', hModuleObject, 'path');
            isrData(m).module = strrep(isrData(m).module, '//DD0/Pool/Modules/', '');
        else
            isrData(m).module = dsdd('GetModuleRef', hIsrObject);
        end
        if dsdd_check_msg(errCode),
            isrData(m).module = '';
        end
        % functionclass
        isrData(m).functionclass = dsdd('GetFunctionClassRef',hIsrObject);
        if isempty(isrData(m).functionclass),
            isrData(m).functionclass = 'default ';
        end
        % category
        [categoryStr,errCode] = dsdd('GetISRCategory',hIsrObject);
        isrData(m).category = find(strcmp(categoryStr, {'CAT1_NO_OS_CALLS', 'CAT2_WITH_OS_CALLS'}));
        if dsdd_check_msg(errCode),
            isrData(m).category = 2;
        end
    end
end

isrInfo.dataStrings  = isrList;
dlgdata.isrInfo = isrInfo;
dlgdata.isrData = isrData;


%--------------------------------------------------------------------------
% FcnApply writes current block data to the DD
%
% INPUT ARGUMENTS
%   - / -
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%--------------------------------------------------------------------------
function FcnApply(dlgdata)

isrInfo = dlgdata.isrInfo;

% DataDictionary path for isrs
ddIsrPath = '/Pool/RTOS/ISRs';

% first delete ISRs
for m = 1:length(isrInfo.deletedIsr),
   dsdd('delete',[ddIsrPath,'/',isrInfo.deletedIsr{m}]);
end

% add new ISR
for m = 1:length(isrInfo.newIsr),
    if ~dsdd('Exist',isrInfo.newIsr{m}, ...
            'Parent',            '/Pool/RTOS/ISRs', ...
            'ObjectKind',        'isr')
        [hIsrObject,errCode] = dsdd('Create',isrInfo.newIsr{m}, ...
            'Parent',            '/Pool/RTOS/ISRs', ...
            'ObjectKind',        'isr');
        if dsdd_check_msg(errCode)
            % don't return if creation failed
            continue
        end
    end
    % append created counters to edited counter
    isrInfo.editedIsr = [isrInfo.editedIsr,isrInfo.newIsr(m)];
end

% apply changes of edited ISRs
editedIsr = unique(isrInfo.editedIsr);
for m = 1:length(editedIsr),
    currentIsrIdx = strcmp(editedIsr{m},isrInfo.dataStrings);
    [bExist,hIsrObject] = dsdd('exist',[ddIsrPath,'/',editedIsr{m}]);
    properties = dlgdata.isrData(currentIsrIdx);
    if bExist,
        % description
        errCode = dsdd('SetDescription',hIsrObject,properties.description);
        dsdd_check_msg(errCode);
        
        % code file
        %--------------------------------------------------------------------------
        % ANNOTATION * MarcoGie* 22-Jan-2009 15:47:49
        %--------------------------------------------------------------------------
        % The call of "dsdd('SetCodeFile',hIsrObject,properties.module)doesn't" 
        % work anymore and has to be exchanged.
        %--------------------------------------------------------------------------
        % error('Obsolete call of dsdd: "dsdd(''SetCodeFile'',hIsrObject,properties.module);"');
        errCode = dsdd('SetModuleRef',hIsrObject,properties.module);
        dsdd_check_msg(errCode);
        % function class
        errCode = dsdd('SetFunctionClassRef',hIsrObject,properties.functionclass);
        dsdd_check_msg(errCode);
        % category
        errCode = dsdd('SetISRCategory',hIsrObject,properties.category);
        dsdd_check_msg(errCode);
   end
end


%-------------------------------------------------------
% FcnSetIsrDefaults
%   creates default data structure for ISRs
%
% INPUT ARGUMENTS
%   isrData         current ISR data struct
%   idx             index of current ISR
%
% OUTPUT ARGUMENTS
%   isrData        initialized ISR data structure
%-------------------------------------------------------
function isrData = FcnSetIsrDefaults(isrData,idx)

isrData(idx).description   = '';
isrData(idx).module      = '';
isrData(idx).functionclass = 'default ';
isrData(idx).category      = 2;
isrData(idx).bValid        = 1;
